# copyright 温州二中 衢州二中 沈文轩等人版权所有
import sqlite3
from datetime import *
from flask import *

app = Flask(__name__)
app.config['SECRET_KEY'] = b'\r\xe1\xe9@m\xcb-\x97r\xa6\x08=\x90J:b:s\x10\xb3\x91\xf9\x0f\xaf'
# app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=30)

conn = sqlite3.connect('data.sqlite', check_same_thread=False)
cur = conn.cursor()

Class_st = 0

Class_tm = 0


# -----------登录网页--------
@app.route('/')
def wel():
    if logged_in():
        return redirect(url_for('system'))
    return redirect(url_for('login'))


# -----登录网页-----
@app.route('/login', methods=['POST', 'GET'])
def login():
    # 正常访问
    if request.method == 'GET':
        if logged_in():
            return redirect(url_for('system'))
        return render_template('login.html')

    # 数据校验
    elif request.method == 'POST':
        data = request.get_json()
        user = data["username"]
        psd = data["password"]
        cur.execute(f'SELECT * FROM Users WHERE Name = "{user}" and Password = "{psd}"')
        res = cur.fetchall()
        print(res)
        if len(res) >= 1:
            response = {
                'status': 'success',
                'message': '登录成功'
            }
            session['Name'] = user
            session['uname'] = user
            resp = redirect('/')
            print(data)
            if data['isSave']:
                resp.set_cookie('uname', user, timedelta(days=30))
                # session.permanent = True
                app.permanent_session_lifetime = timedelta(days=30)
            else:
                # session.permanent = False
                app.permanent_session_lifetime = timedelta(hours=1)
            return jsonify(response)
        else:
            response = {
                'status': 'fail',
                'message': '登录失败'
            }
            return jsonify(response)
    else:
        return "Invalid method"


# ----主页------
@app.route('/system')
def system():
    if not logged_in():
        return redirect(url_for('login'))
    cur.execute("SELECT Score,Time FROM StuClaData")
    res_sk = cur.fetchall()  # 上课数据
    stu_cdt = ''
    stu_cdt_time = ''
    for i in res_sk[::-1]:
        stu_cdt += (str(i[0]) + ',')
    stu_cdt = stu_cdt[:len(stu_cdt) - 1]
    print(stu_cdt)

    for i in res_sk[::-1]:
        stu_cdt_time += (str(i[1])[5:-3] + ',')
    stu_cdt_time = stu_cdt_time[:len(stu_cdt_time) - 1]
    print(stu_cdt_time)

    cur.execute("SELECT judge FROM StuEx")
    dt_cdt = cur.fetchall()
    dt_cdt = [i[0] for i in dt_cdt]

    errors, right = 0, 0
    for i in dt_cdt:
        if i == 'wrong':
            errors += 1
        else:
            right += 1

    print(errors, right)

    return render_template('main.html', **locals())


# ----上课------
@app.route('/class', methods=['GET', 'POST'])
def class_have():
    if not logged_in():
        return redirect('/login')
    return render_template('class_begin.html')


# --------开始上课--------
@app.route('/cbegin', methods=['GET', 'POST'])
def cb():
    global Class_tm
    global Class_st
    if request.method == 'GET':
        if Class_st == 0:  # 未上课
            return jsonify({'status': '0', 'time': '0'})
        else:  # 上课
            return jsonify({'status': '1', 'time': f'{Class_st}'})

    elif request.method == 'POST':
        data = request.get_json()
        setting_time = int(data['time'])
        setting = data['status']
        if setting == 'on':

            Class_tm = 1  # 上课

            Class_st = setting_time

        else:
            Class_tm = 0  # 非课
            Class_st = 0
        print(Class_st, Class_tm)
        return jsonify({'1': 1})
    else:
        return "Illegal method"


# -----------------解析题目-------------------------
@app.route('/get_ex', methods=['GET', 'POST'])
def ex():
    if request.method == 'POST':
        data = request.get_json()
        exer = data['exer']
        ex_a = data['ex_A']
        ex_b = data['ex_B']
        ex_c = data['ex_C']
        ex_d = data['ex_D']
        correct = data['correct']
        # noinspection SqlIdentifier
        cur.execute(
            f'''INSERT INTO exer(Timu,A,B,C,D,right,status) VALUES('{exer}','{ex_a}','{ex_b}','{ex_c}','{ex_d}','{correct}','0')''')
        conn.commit()
        cur.execute("SELECT MAX(id) FROM exer")
        current_id = cur.fetchone()
        _id = current_id
        return jsonify({'status': 'success', 'id': _id})

    elif request.method == 'GET':
        cur.execute("SELECT * FROM exer WHERE status = 0")
        res = cur.fetchone()
        print(f"Ex结果{res}")
        if res is not None:
            mainid = res[0]
            cur.execute(f'''UPDATE exer SET status=1 WHERE id = {mainid}''')
            conn.commit()
            return jsonify({'data': res})

        else:
            return jsonify({'data': 'None'})
    else:
        return "Illegal method"


# -----------------学生提交整节课数据-------------------------
@app.route('/handle', methods=['POST'])
def handle():
    data = request.get_data()
    data = eval(data.decode())

    Normal = data['Normal']
    Distract = data['Distract']
    Time = data['Time']
    Score = data['Score']
    print(data)
    cur.execute(
        f'''INSERT INTO StuClaData(Stuid,Time,Normal,Distract,Score) VALUES(01,'{Time}',{Normal},{Distract},{Score})''')
    conn.commit()

    return jsonify({'status': 'success'})


# -----------------学生提交答题情况数据-------------------------
@app.route('/DT', methods=['POST'])
def dt():
    data = request.get_data()
    data = eval(data.decode())
    # Stuid = data['Stuid']
    Timu = data['Timu']
    Time = data['Time']
    ans = data['ans']
    judge = data['judge']
    print(data)
    cur.execute(f'''INSERT INTO StuEx(Stuid,Timu,Time,ans,judge) \
                VALUES(01,{Timu},'{Time}','{ans}','{judge}')''')
    conn.commit()

    return jsonify({'status': 'success'})


# -----------------老师查看题情况数据-------------------------
@app.route('/getdt', methods=['POST'])
def getdt():
    if not logged_in():
        return redirect('/login')
    req = request.get_json()
    print(req)
    req_id = int(req['id'][0])
    cur.execute(f'SELECT Stuid,Timu,Time,ans,judge FROM StuEx WHERE Timu = {req_id}')
    data = cur.fetchall()
    print(data)
    return jsonify({'data': data})


@app.route('/logout')
def alert_logout():
    if logged_in():
        return redirect('/')
    return "<p>系统已登出。安全起见，你最好关闭所有窗口。</p><a href='/'>再次登录</a>"


# -----------------登出-------------------------
@app.route('/systemlogout')
def systemlogout():
    session.clear()
    resp = redirect('/logout')
    resp.delete_cookie('uname')
    return resp


@app.route('/con')
def con():
    return 0


@app.route('/cEnd')  # 下课
def cend():
    # if 'uname' not in session:
    #     return redirect('/login')
    global Class_tm
    global Class_st
    Class_tm = 0  # 非课
    Class_st = 0
    print("[INFO]下课请求发送")
    return jsonify({'status': 'success'})


@app.route('/StuEXD', methods=['GET', 'POST'])
def StuExd():
    if 'uname' not in session:
        return redirect('/login')
    if request.method == 'GET':
        cur.execute(f"SELECT Stuid, Timu, Time, ans, judge FROM StuEx")
        data = cur.fetchall()[::-1]
        return render_template('StuEx.html', data=data)
    elif request.method == 'POST':
        cur.execute("DELETE FROM StuEx")
        conn.commit()
        return 'success'
    else:
        return "Illegal method"


@app.route('/StuCdt', methods=['GET', 'POST'])
def StuCDT():
    if not logged_in():
        return redirect('/login')
    if request.method == 'GET':
        cur.execute(f"SELECT Stuid, Time, Normal, Distract, Score FROM StuClaData")
        data = cur.fetchall()
        # print(data)
        return render_template('StuCdt.html', data=data[::-1])
    elif request.method == 'POST':
        cur.execute("DELETE FROM StuClaData")
        conn.commit()
        return 'success'
    else:
        return "Illegal method"

@app.route('/account_management', methods=['GET', 'POST'])
def account_management():
    if not logged_in():
        return redirect('/login')
    if request.method == 'POST':
        pwd_data = request.get_json()
        old_pwd = pwd_data['old_pwd']
        new_pwd = pwd_data['new_pwd']
        username = session['uname']
        cur.execute(f'SELECT * FROM Users WHERE name="{username}" and password="{old_pwd}"')
        user = cur.fetchall()
        if len(user) == 0:
            return 'error'
        else:
            cur.execute(f'UPDATE Users SET password="{new_pwd}" WHERE name="{username}"')
            conn.commit()
            return 'success'
    elif request.method == 'GET':
        return render_template('account.html')
    else:
        return "Illegal method"

def logged_in() -> bool:
    if 'uname' not in session:
        return False
    return True

@app.route('/all_timu', methods=['GET', 'POST'])
def all_timu():
    if not logged_in():
        return redirect('/login')
    if request.method == 'GET':
        _id = request.args.get('id')
        if _id is not None:
            cur.execute(f'SELECT id, Timu, A, B, C, D, "right" FROM exer WHERE id = {_id}')
            data = cur.fetchone()
            if data is not None:
                return jsonify(data)
            else:
                return 'invalid_id'
        else:
            cur.execute(f'SELECT id, Timu, A, B, C, D, "right" FROM exer')
            data = cur.fetchall()[::-1]
            return render_template('StuTimu.html', data=data)
    elif request.method == 'POST':
        cur.execute("DELETE FROM exer")
        conn.commit()
        return 'success'
    else:
        return "Illegal method"

# 启动框架实例
if __name__ == '__main__':
    app.run('0.0.0.0', debug=False, port=8888)
